package com.yuexin.project.dailymenu.everyday.controller;

import com.google.common.collect.Maps;
import com.yuexin.common.utils.DateUtils;
import com.yuexin.common.utils.file.FileUploadUtils;
import com.yuexin.common.utils.security.ShiroUtils;
import com.yuexin.framework.aspectj.lang.annotation.Log;
import com.yuexin.framework.aspectj.lang.enums.BusinessType;
import com.yuexin.framework.config.YueXinConfig;
import com.yuexin.framework.web.controller.BaseController;
import com.yuexin.framework.web.domain.AjaxResult;
import com.yuexin.framework.web.page.TableDataInfo;
import com.yuexin.project.dailymenu.dishlist.service.DishIListService;
import com.yuexin.project.dailymenu.everyday.domain.EverydayMenu;
import com.yuexin.project.dailymenu.everyday.export.ExcelReader;
import com.yuexin.project.dailymenu.everyday.export.ExportDayItem;
import com.yuexin.project.dailymenu.everyday.export.ExportError;
import com.yuexin.project.dailymenu.everyday.export.ExportErrorResult;
import com.yuexin.project.dailymenu.everyday.service.IEverydayMenuService;
import com.yuexin.project.dailymenu.menumanager.service.IManagerService;
import com.yuexin.project.system.dict.domain.DictData;
import com.yuexin.project.system.dict.service.IDictDataService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 每日菜单 信息操作处理
 *
 * @author yuexin
 * @date 2018-10-14
 */
@Controller
@RequestMapping("/dailymenu/everyday")
public class EverydayMenuController extends BaseController {
    private String prefix = "dailymenu/everyday";

    @Autowired
    private IEverydayMenuService everydayMenuService;

    @Autowired
    private IManagerService managerService;

    @Autowired
    private DishIListService listService;

    @Autowired
    private IDictDataService dataService;


    @RequiresPermissions("dailymenu:everydayMenu:view")
    @GetMapping()
    public String everydayMenu() {
        return prefix + "/everyday";
    }

    private String getDishName(EverydayMenu everydayMenu) {
        String dishNames = "";
        everydayMenu.setCompanyId(ShiroUtils.getCompanyId());
        List<String> nameList = listService.selectDailyMenuDishList(everydayMenu);
        if (nameList != null && nameList.size() > 0) {
            for (String name : nameList) {
                dishNames += name;
                dishNames = dishNames + "、";
            }
        }

        if (!"".equals(dishNames) && dishNames != null) {
            dishNames = dishNames.substring(0, dishNames.length() - 1);
        }
        return dishNames;
    }

    /**
     * 查询每日菜单列表
     */
    @RequiresPermissions("dailymenu:everydayMenu:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(EverydayMenu everydayMenu) {
        //startPage();
        Calendar cale = Calendar.getInstance();
        return getEveryDay(everydayMenu, cale.get(Calendar.YEAR), cale.get(Calendar.MONTH) + 1);
    }

    /**
     * java 获取 获取某年某月 所有日期（yyyy-mm-dd格式字符串）
     *
     * @param year
     * @param month
     * @return
     */
    public List<String> getMonthFullDay(int year, int month) {
        SimpleDateFormat dateFormatYYYYMMDD = new SimpleDateFormat("yyyy-MM-dd");
        List<String> fullDayList = new ArrayList<>(32);
        // 获得当前日期对象
        Calendar cal = Calendar.getInstance();
        cal.clear();// 清除信息
        cal.set(Calendar.YEAR, year);
        // 1月从0开始
        cal.set(Calendar.MONTH, month - 1);
        // 当月1号
        cal.set(Calendar.DAY_OF_MONTH, 1);
        int count = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        for (int j = 1; j <= count; j++) {
            fullDayList.add(dateFormatYYYYMMDD.format(cal.getTime()));
            cal.add(Calendar.DAY_OF_MONTH, 1);
        }
        return fullDayList;
    }

    private Integer getDays(Integer year, Integer month) {
        Calendar c = Calendar.getInstance();
        c.set(year, month, 0); //输入类型为int类型
        return c.get(Calendar.DAY_OF_MONTH);
    }

    private boolean hasDay(String day, List<EverydayMenu> list) {
        boolean result = false;
        for (EverydayMenu eMenu : list) {
            Date dailyDate = eMenu.getDailyDate();
            String dailyDateStr = DateUtils.dateTime(dailyDate);
            if (day.equals(dailyDateStr)) {
                result = true;
                break;
            }
        }
        return result;
    }

    /**
     * 查询每日菜单列表(根据月份)
     */
    @PostMapping("/listMonth")
    @ResponseBody
    public TableDataInfo listMonth(EverydayMenu everydayMenu, @RequestParam String year, @RequestParam String month) {
        //去掉分页
        //startPage();
        return getEveryDay(everydayMenu, Integer.parseInt(year), Integer.parseInt(month));
    }

    /**
     * 查询每日菜单列表
     * @param everydayMenu
     * @param year
     * @param month
     * @return
     */
    private TableDataInfo getEveryDay (EverydayMenu everydayMenu, Integer year, Integer month){

        Integer days = getDays(year, month);
        Map<String, Object> params = Maps.newHashMap();
        params.put("beginTime", year + "-" + month + "-" + 01);
        params.put("endTime", year + "-" + month + "-" + days);
        everydayMenu.setParams(params);

        everydayMenu.setCompanyId(ShiroUtils.getCompanyId());
        List<EverydayMenu> list = everydayMenuService.selectEverydayMenuList(everydayMenu);

        //获取月的全部天数,将没有的天自动插入到数据库
        List<String> daysList = getMonthFullDay(year, month);
        for (String day : daysList) {
            EverydayMenu everydayBean = new EverydayMenu();
            everydayBean.setDailyDate(DateUtils.dateTime(DateUtils.YYYY_MM_DD, day));
            setOpen(everydayBean);
            everydayBean.setCompanyId(ShiroUtils.getCompanyId());
            if (hasDay(day, list)) {
                continue;
            } else {
                everydayMenuService.insertEverydayMenu(everydayBean);
            }
        }

        list = everydayMenuService.selectEverydayMenuList(everydayMenu);
        setButtonName(list);
        return getDataTable(list);
    }

    /**
     * 查询每日菜单列表(按周查询)
     */
    @PostMapping("/listWeek")
    @ResponseBody
    public TableDataInfo listWeek(EverydayMenu everydayMenu, @RequestParam String begin, @RequestParam String end) {
        //startPage();
        String beginStr = begin.replace("/", "-");
        String endStr = end.replace("/", "-");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("beginTime", beginStr);
        params.put("endTime", endStr);
        everydayMenu.setParams(params);

        everydayMenu.setCompanyId(ShiroUtils.getCompanyId());
        List<EverydayMenu> list = everydayMenuService.selectEverydayMenuList(everydayMenu);
        setButtonName(list);
        return getDataTable(list);
    }

    private void setButtonName(List<EverydayMenu> list) {
        String name;
        for (EverydayMenu mn : list) {
            if ("1".equals(mn.getIsBreakFast())) {
                mn.setDinnerType("0");
                name = getDishName(mn);
                mn.setIsBreakFast(name == null || "".equals(name) ? "点击选择菜品" : name);
            }
            if ("1".equals(mn.getIsLunch())) {
                mn.setDinnerType("1");
                name = getDishName(mn);
                mn.setIsLunch(name == null || "".equals(name) ? "点击选择菜品" : name);
            }
            if ("1".equals(mn.getIsDinner())) {
                mn.setDinnerType("2");
                name = getDishName(mn);
                mn.setIsDinner(name == null || "".equals(name) ? "点击选择菜品" : name);
            }
            if ("1".equals(mn.getIsOther())) {
                mn.setDinnerType("3");
                name = getDishName(mn);
                mn.setIsOther(name == null || "".equals(name) ? "点击选择菜品" : name);
            }
        }
    }

    /**
     * 新增每日菜单
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        mmap.put("menus", managerService.selectMenuAll(ShiroUtils.getCompanyId()));
        return prefix + "/add";
    }

    /**
     * 新增保存每日菜单
     */
    @RequiresPermissions("dailymenu:everydayMenu:add")
    @Log(title = "每日菜单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(EverydayMenu everydayMenu) {
        if ("1".equals(everydayMenu.getIsOpen())) {
            setOpen(everydayMenu);
        } else {
            setUnOpen(everydayMenu);
        }
        everydayMenu.setCompanyId(ShiroUtils.getCompanyId());
        return toAjax(everydayMenuService.insertEverydayMenu(everydayMenu));
    }

    /**
     * 修改每日菜单
     */
    @GetMapping("/edit/{dailyId}")
    public String edit(@PathVariable("dailyId") Integer dailyId, ModelMap mmap) {
        EverydayMenu everydayMenu = everydayMenuService.selectEverydayMenuById(dailyId);
        if ("1".equals(everydayMenu.getIsBreakFast()) || "1".equals(everydayMenu.getIsLunch()) || "1".equals(everydayMenu.getIsDinner()) || "1".equals(everydayMenu.getIsOther())) {
            everydayMenu.setIsOpen("1");
        } else {
            everydayMenu.setIsOpen("0");
        }
        mmap.put("everydayMenu", everydayMenu);
        mmap.put("menus", managerService.selectMenuAll(ShiroUtils.getCompanyId()));
        return prefix + "/edit";
    }

    /**
     * 修改保存每日菜单
     */
    @RequiresPermissions("dailymenu:everydayMenu:edit")
    @Log(title = "每日菜单", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(EverydayMenu everydayMenu) {
        if ("1".equals(everydayMenu.getIsOpen())) {
            setOpen(everydayMenu);
        } else {
            setUnOpen(everydayMenu);
            everydayMenu.setMenuId(-1);
        }
        everydayMenu.setCompanyId(ShiroUtils.getCompanyId());
        return toAjax(everydayMenuService.updateEverydayMenu(everydayMenu));
    }

    private void setOpen(EverydayMenu everydayMenu) {
        everydayMenu.setIsBreakFast("1");
        everydayMenu.setIsLunch("1");
        everydayMenu.setIsDinner("1");
        everydayMenu.setIsOther("1");
    }

    private void setUnOpen(EverydayMenu everydayMenu) {
        everydayMenu.setIsBreakFast("0");
        everydayMenu.setIsLunch("0");
        everydayMenu.setIsDinner("0");
        everydayMenu.setIsOther("0");
    }

    /**
     * 删除每日菜单
     */
    @RequiresPermissions("dailymenu:everydayMenu:remove")
    @Log(title = "每日菜单", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(everydayMenuService.deleteEverydayMenuByIds(ids));
    }

    /**
     * 编辑菜单菜品
     */
    @GetMapping("/dish/{dailyId}/{dinnerType}")
    public String dish(@PathVariable("dailyId") Integer dailyId, @PathVariable("dinnerType") String dinnerType, ModelMap mmap) {

        EverydayMenu everydayMenu = everydayMenuService.selectEverydayMenuById(dailyId);
        String isOpen = "0";
        if ("0".equals(dinnerType) & "1".equals(everydayMenu.getIsBreakFast())) {
            isOpen = "1";
        } else if ("1".equals(dinnerType) & "1".equals(everydayMenu.getIsLunch())) {
            isOpen = "1";
        } else if ("2".equals(dinnerType) & "1".equals(everydayMenu.getIsDinner())) {
            isOpen = "1";
        } else if ("3".equals(dinnerType) & "1".equals(everydayMenu.getIsOther())) {
            isOpen = "1";
        }
        everydayMenu.setIsOpen(isOpen);
        everydayMenu.setDinnerType(dinnerType);
        mmap.put("menu", everydayMenu);

        return prefix + "/dish";
    }

    /**
     * 修改保存数据权限
     */
    @RequiresPermissions("dailymenu:everydayMenu:edit")
    @Log(title = "菜单管理管理", businessType = BusinessType.UPDATE)
    @PostMapping("/rule")
    @ResponseBody
    public AjaxResult ruleSave(EverydayMenu everydayMenu) {
        return toAjax(everydayMenuService.updateRule(everydayMenu));
    }

    private  String getDinerType(String type) {
        DictData data = new DictData();
        data.setDictType("dinner_type");
        List<DictData> dictDataList = dataService.selectDictDataList(data);
        if (dictDataList != null) {
            for (DictData data1 : dictDataList) {
                if (data1.getDictValue().equals(type)) {
                    return data1.getDictLabel();
                }
            }
        }
        return "";
    }

    @RequiresPermissions("dailymenu:everydayMenu:edit")
    @GetMapping("/import")
    public String importPage(String begin, String end, String index, ModelMap mmap  ) {
        begin = begin.replace("/", "-");
        String lst[]=begin.split("-");
        end = end.replace("/", "-");
        mmap.put("begin", begin);
        mmap.put("end", end);
        mmap.put("index", index);
        mmap.put("year", lst[0]);
        mmap.put("dinerType", getDinerType(index));
        mmap.put("yearOfweek", ExcelReader.getWeekOfYear(begin));
        mmap.put("excelDownUrl", "/meals/"+prefix+"/downLoadExcel?begin="+begin+"&end="+end+"&dinnerType="+index+"&");

        return prefix + "/import";
    }

    @RequiresPermissions("dailymenu:everydayMenu:edit")
    @PostMapping("/doImport")
    public String  doImport( String dinnerType  , int replaceIt, String begin ,String end,@RequestParam("file") MultipartFile file, ModelMap mmap  ) {
        ExportErrorResult exportErrorResult = new ExportErrorResult();
        List<ExportError> errorList = new ArrayList<>();
        try {

            if (!file.isEmpty()) {

                String filename = file.getOriginalFilename();
                int index = filename.indexOf(".");
                String extName = filename;
                if (index != -1) {
                    extName = filename.substring(index);
                }
                String companyId = ShiroUtils.getCompanyId();
                File uploadFile = FileUploadUtils.uploadFile(YueXinConfig.getDownloadPath(), file, extName);
                exportErrorResult = everydayMenuService.exportExcel(uploadFile.getAbsolutePath(), companyId, dinnerType, replaceIt);
                errorList=exportErrorResult.getErrorList();
            } else {
                ExportError error = new ExportError();
                error.setLine("1");
                error.setErrorMsg("excel内容为空!");
                errorList.add(error);
            }

        } catch (Exception ex) {
            ExportError error = new ExportError();
            error.setLine("1");
            error.setErrorMsg("系统错误" + ex.getMessage());
            errorList.add(error);

            ex.printStackTrace();
        }


        begin = begin.replace("/", "-");
        String lst[] = begin.split("-");
        end = end.replace("/", "-");
        mmap.put("begin", begin);
        mmap.put("end", end);
        mmap.put("index", dinnerType);
        mmap.put("year", lst[0]);
        mmap.put("dinerType", getDinerType(dinnerType));
        mmap.put("yearOfweek", ExcelReader.getWeekOfYear(begin));
        mmap.put("href", "/meals/" + prefix + "/import?begin=" + begin + "&end=" + end + "&index=" + dinnerType + "&");
        mmap.addAttribute("errorList", exportErrorResult.getErrorList());
        mmap.put("errorList", errorList);
        return prefix + "/importPage";
    }

    @RequiresPermissions("dailymenu:everydayMenu:edit")
    @GetMapping("/downLoadExcel")
    @ResponseBody
    public void  downLoadExcel( String begin, String end, String dinnerType ,HttpServletResponse response ) {
        begin = begin.replace("/", "-");
        String lst[] = begin.split("-");
        end = end.replace("/", "-");
        String companyId = ShiroUtils.getCompanyId();

        List<ExportDayItem> exportDayItemList = everydayMenuService.getExportMenuList(begin, end, companyId, dinnerType);
        String dinnerTypeName = getDinerType(dinnerType);
        String now=DateUtils.dateTimeNow();
        ExcelReader.setFileName("排餐导出" + dinnerTypeName + "模板"+now+".xls", response);
        HSSFWorkbook wb = ExcelReader.writeExcel(dinnerTypeName, exportDayItemList);

        try {
            OutputStream out = response.getOutputStream();
            wb.write(out);
        } catch (Exception ex) {
            ex.printStackTrace();

        } finally {
            if (wb != null) {
                try {
                    wb.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }





    public static void main(String[] args) throws ParseException {
        String begin = "2019/1/1";
        String bString = begin.replace("/", "-");
        System.out.println("bString--" + bString);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = sdf.parse(bString);
            System.out.println("date--" + date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
